<template>
  <div class="sales-order-smart-alerts" v-if="alerts.length > 0">
    <el-card class="alerts-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Bell /></el-icon>
          <span>销售订单智能提醒</span>
        </div>
      </template>
      <div class="alerts-content">
        <div 
          v-for="alert in alerts" 
          :key="alert.id"
          class="alert-item"
          :class="`alert-${alert.type}`"
          @click="handleAlertClick(alert)"
        >
          <el-icon :size="16" :color="getAlertColor(alert.type)">
            <component :is="getAlertIcon(alert.type)" />
          </el-icon>
          <div class="alert-text">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-description">{{ alert.description }}</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Bell, Warning, Document, TrendCharts, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Alert {
  id: string
  type: 'duplicateInvoice' | 'largeAmount' | 'frequentInvoice' | 'abnormal'
  title: string
  description: string
  priority: 'high' | 'medium' | 'low'
  orders?: any[]
}

interface Props {
  orders: any[]
}

const props = defineProps<Props>()
const emit = defineEmits(['alert-click'])

// 计算智能提醒
const alerts = computed(() => {
  // 确保orders是数组
  const orders = Array.isArray(props.orders) ? props.orders : []
  
  const alerts: Alert[] = []
  
  // 检查重复开票
  const duplicateInvoices = checkDuplicateInvoices(orders)
  if (duplicateInvoices.length > 0) {
    alerts.push({
      id: 'duplicate-invoices',
      type: 'duplicateInvoice',
      title: `发现${duplicateInvoices.length}笔重复开票`,
      description: '同一客户短期内存在重复开票，请核实',
      priority: 'high',
      orders: duplicateInvoices
    })
  }
  
  // 检查大额订单
  const largeAmountOrders = checkLargeAmountOrders(orders)
  if (largeAmountOrders.length > 0) {
    alerts.push({
      id: 'large-amount-orders',
      type: 'largeAmount',
      title: `发现${largeAmountOrders.length}笔大额订单`,
      description: '订单金额较大，请关注资金回笼情况',
      priority: 'medium',
      orders: largeAmountOrders
    })
  }
  
  // 检查频繁开票客户
  const frequentCustomers = checkFrequentInvoiceCustomers(orders)
  if (frequentCustomers.length > 0) {
    alerts.push({
      id: 'frequent-customers',
      type: 'frequentInvoice',
      title: `发现${frequentCustomers.length}个频繁开票客户`,
      description: '部分客户短期内开票频率较高，请关注',
      priority: 'medium',
      orders: frequentCustomers
    })
  }
  
  return alerts
})

// 检查重复开票（同一客户24小时内重复开票）
const checkDuplicateInvoices = (orders: any[]) => {
  if (!orders || !Array.isArray(orders)) return []
  const duplicateOrders: any[] = []
  const customerInvoices: Record<string, any[]> = {}
  
  // 按客户分组订单
  orders.forEach(order => {
    if (order && order.customerId) {
      if (!customerInvoices[order.customerId]) {
        customerInvoices[order.customerId] = []
      }
      const customerGroup = customerInvoices[order.customerId]
      if (customerGroup) {
        customerGroup.push(order)
      }
    }
  })
  
  // 检查每个客户的重复开票
  Object.keys(customerInvoices).forEach(customerId => {
    const customerOrders = customerInvoices[customerId]
    if (customerOrders && Array.isArray(customerOrders) && customerOrders.length > 1) {
      // 按时间排序
      customerOrders.sort((a, b) => {
        const timeA = a && a.createTime ? new Date(a.createTime).getTime() : 0
        const timeB = b && b.createTime ? new Date(b.createTime).getTime() : 0
        return timeA - timeB
      })
      
      // 检查24小时内是否有重复开票
      for (let i = 0; i < customerOrders.length - 1; i++) {
        const currentOrder = customerOrders[i]
        const nextOrder = customerOrders[i + 1]
        
        if (currentOrder && nextOrder && currentOrder.createTime && nextOrder.createTime) {
          const timeDiff = new Date(nextOrder.createTime).getTime() - new Date(currentOrder.createTime).getTime()
          // 24小时内重复开票
          if (timeDiff < 24 * 60 * 60 * 1000) {
            duplicateOrders.push(currentOrder, nextOrder)
          }
        }
      }
    }
  })
  
  return [...new Set(duplicateOrders)] // 去重
}

// 检查大额订单（超过10万元）
const checkLargeAmountOrders = (orders: any[]) => {
  if (!orders || !Array.isArray(orders)) return []
  return orders.filter(order => order && order.orderAmount && order.orderAmount > 100000)
}

// 检查频繁开票客户（24小时内同一客户开票超过3次）
const checkFrequentInvoiceCustomers = (orders: any[]) => {
  if (!orders || !Array.isArray(orders)) return []
  const frequentCustomers: any[] = []
  const customerInvoiceCount: Record<string, { count: number, orders: any[] }> = {}
  
  // 统计每个客户24小时内的开票次数
  orders.forEach(order => {
    if (order && order.customerId) {
      if (!customerInvoiceCount[order.customerId]) {
        customerInvoiceCount[order.customerId] = { count: 0, orders: [] }
      }
      const customerData = customerInvoiceCount[order.customerId]
      if (customerData) {
        customerData.count++
        customerData.orders.push(order)
      }
    }
  })
  
  // 筛选开票次数超过3次的客户
  Object.keys(customerInvoiceCount).forEach(customerId => {
    const customerData = customerInvoiceCount[customerId]
    if (customerData && customerData.count > 3) {
      frequentCustomers.push(...customerData.orders)
    }
  })
  
  return frequentCustomers
}

// 获取提醒图标
const getAlertIcon = (type: string) => {
  const icons: Record<string, any> = {
    duplicateInvoice: Warning,
    largeAmount: TrendCharts,
    frequentInvoice: Document,
    abnormal: InfoFilled
  }
  return icons[type] || Bell
}

// 获取提醒颜色
const getAlertColor = (type: string) => {
  const colors: Record<string, string> = {
    duplicateInvoice: '#f5222d',
    largeAmount: '#fa8c16',
    frequentInvoice: '#faad14',
    abnormal: '#1890ff'
  }
  return colors[type] || '#1890ff'
}

// 处理提醒点击
const handleAlertClick = (alert: Alert) => {
  ElMessage.info(`查看${alert.title}`)
  emit('alert-click', alert)
}
</script>

<style scoped lang="scss">
.sales-order-smart-alerts {
  margin-bottom: 20px;
  
  .alerts-card {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    
    :deep(.el-card__header) {
      padding: 12px 20px;
      border-bottom: 1px solid #ebeef5;
      
      .card-header {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        color: #1f2d3d;
      }
    }
    
    .alerts-content {
      .alert-item {
        display: flex;
        align-items: flex-start;
        gap: 12px;
        padding: 12px 16px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &:hover {
          background-color: #f5f7fa;
          transform: translateX(2px);
        }
        
        &.alert-duplicateInvoice {
          border-left: 3px solid #f5222d;
        }
        
        &.alert-largeAmount {
          border-left: 3px solid #fa8c16;
        }
        
        &.alert-frequentInvoice {
          border-left: 3px solid #faad14;
        }
        
        &.alert-abnormal {
          border-left: 3px solid #1890ff;
        }
        
        .alert-text {
          flex: 1;
          
          .alert-title {
            font-weight: 500;
            color: #1f2d3d;
            margin-bottom: 4px;
            font-size: 14px;
          }
          
          .alert-description {
            font-size: 12px;
            color: #606266;
            line-height: 1.4;
          }
        }
      }
    }
  }
}
</style>